import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Switch,
  message,
  Segmented,
  Tooltip,
} from "antd";
import {
  SettingOutlined,
  DeleteOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import {
  GlobalOutlined,
  HomeOutlined,
  BlockOutlined,
  WarningOutlined,
} from "@ant-design/icons";
import { invoke } from "@tauri-apps/api/core";

import AddProxieModal from "./AddProxieModal";
import EditProxieModal from "./EditProxieModal";

interface Service {
  id: string;
  name: string;
  custom_domains: string[];
  local_ip: string;
  local_port: number;
  status: "1" | "0";
  proxy_type: "tcp" | "udp" | "http" | "tcpmux";
  err?: string;
}

const typeOptions = ["tcp", "udp", "http", "tcpmux"];

const Index: React.FC = () => {
  const [services, setServices] = useState<Service[]>([]);
  const [filter, setFilter] = useState<string>("all");
  const [editingService, setEditingService] = useState<Service | null>(null);
  const [addModalVisible, setAddModalVisible] = useState(false);

  useEffect(() => {
    handleGetList();
  }, []);

  const handleGetList = async () => {
    const proxies: any = await invoke("get_setting", {
      path: "client.config.proxies",
    });
    console.log("proxies", proxies);
    const services = proxies.data.map((p: any) => ({
      id: p.id,
      name: p.name,
      custom_domains: p.custom_domains || [],
      local_ip: p.local_ip || "",
      local_port: Number(p.local_port) || 0,
      status: p.status,
      proxy_type: typeOptions.includes(p.proxy_type) ? p.proxy_type : "tcp",
      err: p.err || "",
    }));
    setServices(services);
  };

  const handleDelProxie = async (id: string) => {
    let result: any = await invoke("del_proxie", { id: id });
    if (result.code == 1) {
      message.success("删除成功");
      handleGetList();
    } else {
      message.error("删除失败");
    }
  };

  const handleChangeStatus = async (id: string, checked: boolean) => {
    let result: any = await invoke("save_status", {
      id: id,
      status: checked ? 1 : 0,
    });
    if (result.code) {
      handleGetList();
      message.success(result.msg);
    } else {
      message.error(result.msg);
    }
  };

  const filteredServices = services.filter((s) =>
    filter === "all" ? true : s.proxy_type === filter
  );

  return (
    <div style={{ padding: 20 }}>
      <div style={{ marginBottom: 20, textAlign: "center" }}>
        <Segmented
          options={["all", ...typeOptions].map((p) => ({
            label: p.toUpperCase(),
            value: p,
          }))}
          value={filter}
          onChange={(val) => setFilter(val as string)}
        />
      </div>

      <Row gutter={[12, 12]}>
        {/* 新增服务卡片 */}
        <Col xs={24} sm={12} md={8} lg={6} xl={4} key="add-card">
          <Card
            hoverable
            style={{
              border: "1px dashed #d9d9d9",
              textAlign: "center",
              minWidth: 180,
              minHeight: 180,
              width: "100%", // 保证和其他卡片一致宽度
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
            }}
            onClick={() => setAddModalVisible(true)}
          >
            <PlusOutlined style={{ fontSize: 32, color: "#999" }} />
            <div style={{ marginTop: 8, color: "#999" }}>新增服务</div>
          </Card>
        </Col>

        {/* 已有服务卡片 */}
        {filteredServices.map((service) => (
          <Col xs={24} sm={12} md={8} lg={6} xl={4} key={service.id}>
            <Card
              title={service.name}
              hoverable
              style={{
                minWidth: 180,
                minHeight: 180,
                width: "100%", // 保证和新增卡片一致宽度
                display: "flex",
                flexDirection: "column",
                justifyContent: "flex-start",
              }}
              extra={
                <Switch
                    checked={service.status == "1"}
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                    onChange={(checked) => {
                      handleChangeStatus(service.id, checked);
                    }}
                  />
              }
              actions={[
                <Tooltip title="编辑后请重启服务！" key="edit">
                  <SettingOutlined onClick={() => setEditingService(service)} />
                </Tooltip>,
                <Tooltip title="删除后无法找回！" key="delete">
                  <DeleteOutlined
                    style={{ color: "#F56C6C" }}
                    onClick={() => handleDelProxie(service.id)}
                  />
                </Tooltip>,
              ]}
            >
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <GlobalOutlined style={{ color: "#1890ff" }} />
                  {service.custom_domains.length > 0 ? (
                    service.custom_domains.join(", ")
                  ) : (
                    <span style={{ color: "#999" }}>暂无</span>
                  )}
                </div>

                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <HomeOutlined style={{ color: "#52c41a" }} />
                  {service.local_ip}:{service.local_port}
                </div>

                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <BlockOutlined style={{ color: "#faad14" }} />
                  {service.proxy_type.toUpperCase()}
                </div>

                {service.err && (
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                      color: "red",
                      fontSize: 12,
                    }}
                  >
                    <WarningOutlined />
                    错误信息: {service.err}
                  </div>
                )}
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 新增 */}
      <AddProxieModal
        visible={addModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onSuccess={handleGetList}
      />

      {/* 编辑 */}
      {editingService && (
        <EditProxieModal
          service={editingService}
          onCancel={() => setEditingService(null)}
          onSuccess={() => {
            setEditingService(null);
            handleGetList();
          }}
        />
      )}

      {/* 重启提示 */}
    </div>
  );
};

export default Index;
